'''
Created on 2009-12-18

@author: wangjo
'''
#!/user/bin/python

import os
import logging
import re
import optparse

LOG_FILENAME = 'D:\cbn\converter.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)

def main():
    in_dir = 'D:\cbn\cbnvideos-78\cbnvideos'
    usage = "usage: %prog [options]"
    parser = optparse.OptionParser(usage)
    parser.add_option("-i", "--input", dest="input", help="input directory", metavar="INPUT")
    parser.add_option("-o", "--output", dest="output", help="output directory", metavar="OUTPUT")
    options,args = parser.parse_args()
    if not options.input:
        options.input = in_dir
    logging.info('input: %s' % options.input)
    if not options.output:
        parser.error("Must specify filename and output")
    if options.output:
        if not os.path.isdir(options.output):
            logging.error('outpput is not valid directory')
            return
    logging.info('output : %s' % options.output)
    videos = getVideos(options.input)
    msg = 'Total video count: %d' % len(videos)
    logging.info(msg)
    print msg
    index = 0
    for video in videos:
        index = index +1
        msg = 'Current %(index)d / %(total)d'% {'index':index, 'total':len(videos)}
        logging.info(msg)
        print msg
        convert(video, options.output)
        
    #wait on the queue until everything has been processed     
    #queue.join()

    msg = 'All videos converting finished'
    logging.info(msg)
    print msg
    
def getVideos(inputdir):
    files = []
    for dirname, dirnames, filenames in os.walk(inputdir):
        for filename in filenames:
            file = os.path.join(dirname, filename)
            files.append(file)
    return files

def call_command(command):
    try:
        import subprocess
        process = subprocess.Popen(command.split(' '),
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
        process.communicate()
        return process.returncode
    except ImportError, e:
        logging.info('does not support subprocess module:%s')
        return os.system(command)
       
def convert(inputfile, outputdir):
    logging.info('start convert video: %s' % inputfile)
    splits = inputfile.split('\\')
    filename = splits[len(splits)-1]
    pattern = '^(\d+){1}'
    items = filename.split('.')
    items[len(items)-1] = 'mp4'
    newfilename = '.'.join(items)
    match = re.match(pattern, filename)
    if match:
        datestr = match.groups(0)[0]
        targetfolder = os.path.join(outputdir, datestr)
        if not os.path.exists(targetfolder):
            try:
                os.makedirs(targetfolder)
            except OSError:
                logging.error('create folder failed')
        target = os.path.join(targetfolder, newfilename)
        handbrake(inputfile, target)
        
def handbrake(input, output):
    cmdhandbrake = 'C:\Users\wangjo\Downloads\HandBrake-0.9.4-Win_CLI\HandBrakeCLI.exe'
    cmd = '%(handbrake)s -i %(input)s -o %(output)s --preset="iPhone & iPod Touch"' % {'handbrake': cmdhandbrake, 'input':input, 'output':output}
    msg = 'handbrake command: %s' % cmd
    logging.info(msg)
    print msg
    retcode = call_command(cmd)
    #retcode = 0
    if retcode == 0:
        msg = 'convert video successful: %s' % output
        logging.info(msg)
    else:
        msg = 'convert video failed :%s' % output
        logging.error(msg)
if __name__ == "__main__":
    main()